<template>
  <div class="memeory-bg word-listen-bg">
    <Header :isTransBg="true" :width="1000" :isGoBack="false">
      <template v-slot:left>
        <span class="weight-title">
          {{ checkedBookData.edition_name }}-{{ checkedBookData.grade_name }}
        </span>
      </template>
      <template v-slot:right>
        <div class="help-btn mr10" @click="memoryHelpDialog = true">
          <img
            class="ml5"
            slot="reference"
            src="@/assets/img/icon/help-normal.png"
            alt=""
          />
        </div>
        <div class="close-memeory" @click="goStudyCenter">
          关闭
          <img class="ml5" src="@/assets/img/close-circle.png" alt="" />
        </div>
      </template>
    </Header>
    <div class="memory-container w1000">
      <div class="memory-contain">
        <div class="memory-question">
          <div>
            <div class="memory-header">
              智能词听
              <span class="fr reminder-text">
                <span class="feedback-btn ml10 click" @click="showFeedBack">
                  反馈
                </span>
              </span>
            </div>
            <StudyWord
              v-if="wordData.word_id"
              :wordData="wordData"
              @nextWord="nextWord"
              @checkFalseFun="checkFalseFun"
              @closeTimer="closeTimer"
              :category="1"
              ref="studyWord"
            ></StudyWord>
          </div>
        </div>
        <div v-if="wordData.word_id">
          <span>
            <!-- 倒计时：{{ countTimerNum }}  -->
          </span>
          <span v-if="!isReview">
            本次学习：生词：{{ newWordNum }} 熟词：{{ skilledNum }} 本次复习：{{
              reviewNum
            }}
          </span>
          <div v-if="isReview">
            <span></span>
            <span>
              进度：{{ checkedWordIndex + 1 }} /
              {{ wordList.length }}
            </span>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="帮助"
      :visible.sync="memoryHelpDialog"
      width="800px"
      class="memory-help"
    >
      <div>
        <div>
          <div class="mb30">
            <img src="@/assets/img/step-study-2.png" alt="" />
          </div>
          <div class="mb10">
            <img src="@/assets/img/step-study-1.png" alt="" />
          </div>
          <el-divider></el-divider>
          <div></div>
        </div>
        <div>
          <div class="key-point">
            <label>
              <span class="line"></span>
              <span>关键点:</span>
            </label>
            <div>
              <p class="point-info">点击认识或不认识一定要真实;</p>
              <p class="point-info">
                跟读时，
                <span class="red-color-text">单词+词义</span
                >一定要连起来，读出声;
              </p>
              <p class="point-info">
                认识的单词读<span class="red-color-text">一遍英文+一遍中文</span
                >；
              </p>
              <p class="point-info">
                不认识的单词读两轮，每一轮读<span class="red-color-text">四遍英文+一遍中文</span
                >；
              </p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <Feedback ref="feedback" :type="1" :classify="1"></Feedback>
  </div>
</template>
<script>
import Header from "@/components/Header";
import StudyWord from "../components/StudyWord";
import Feedback from "@/components/Feedback";
import EventBus from "@/assets/js/eventBus";
// import { throttle } from "@/utils/utils";
import {
  getStudyWordList,
  setEstimateWord,
  getMemoryReview,
  setWordPass,
  addIntegral,
  getReviewNumber,
} from "@/api/index";
export default {
  data() {
    return {
      wordList: [],
      wordData: {},
      checkedWordIndex: -1,
      groupData: {},
      initSkilledNum: 0,
      initReviewNum: 0,
      initNewWordNum: 0,
      countTimer: null,
      countTimerNum: 5,
      unitId: null,
      isReview: false,
      category: 1,
      checkedBookData: null,
      addIntegralNum: 0,
      memoryHelpDialog: false,
      isOpenMessageBox: false,
    };
  },
  computed: {
    skilledNum() {
      let data = this.wordList.filter((item) => {
        return !item.isReview && item.checkAnswer === true;
      });
      return data.length + this.initSkilledNum;
    },
    reviewNum() {
      let data = this.wordList.filter((item) => {
        return (
          item.isReview &&
          (item.checkAnswer === true || item.checkAnswer === false)
        );
      });
      return data.length + this.initReviewNum;
    },
    newWordNum() {
      let data = this.wordList.filter((item) => {
        return !item.isReview && item.checkAnswer === false;
      });
      return data.length + this.initNewWordNum;
    },
  },
  methods: {
    setInitWordNum() {
      let data1 = this.wordList.filter((item) => {
        return !item.isReview && item.checkAnswer === true;
      });
      let data2 = this.wordList.filter((item) => {
        return (
          item.isReview &&
          (item.checkAnswer === true || item.checkAnswer === false)
        );
      });
      let data3 = this.wordList.filter((item) => {
        return !item.isReview && item.checkAnswer === false;
      });
      this.initSkilledNum += data1.length;
      this.initReviewNum += data2.length;
      this.initNewWordNum += data3.length;
    },
    showFeedBack() {
      if (this.wordData.word_id) {
        this.$refs.feedback.visible(this.wordData.word_id);
      }
    },
    addIntegral(groupId) {
      let params = {
        groupId,
        source: this.category,
        bookId: this.checkedBookData.book_id,
        unitId: this.unitId,
        type: 1,
      };
      addIntegral(params).then((res) => {
        if (res.code == 200) {
          this.addIntegralNum += res.data;
        }
      });
    },
    //  需要复习的单词两个之后插一个，标记isReview:true
    nextWord: function() {
      if (this.wordList.length <= 0) {
        return;
      }
      //
      if (
        this.checkedWordIndex < this.wordList.length - 1 &&
        this.wordList.length > 0
      ) {
        this.checkedWordIndex++;
        this.setWordData(this.wordList[this.checkedWordIndex]);
      } else {
        this.getStudyData();
      }
    },
    setWordData(data) {
      this.wordData = data;
      this.wordData.startTime = new Date().getTime();
      // this.setCountTimer();
      this.$nextTick(() => {
        if (this.$refs.studyWord) {
          this.$refs.studyWord.playAudio("audioPlay");
        }
      });
    },
    setEstimateWord(not) {
      return new Promise((reslove, reject) => {
        let data = {
          not: not,
          bookId: this.checkedBookData.book_id,
          number: this.checkedBookData.number,
          unitId: this.unitId,
          wordId: this.wordData.word_id,
          groupId: this.groupData.group_id,
          category: this.category,
          useTime: parseInt(
            (this.wordData.endTime - this.wordData.startTime) / 1000
          ),
          wid: this.wordData.wid,
          isStrange: this.wordData.isReview ? 1 : 0,
        };
        setEstimateWord(data)
          .then((res) => {
            reslove(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    setWordPass() {
      return new Promise((reslove, reject) => {
        let num = this.wordList.filter((item) => {
          return item.id == this.wordData.id;
        }).length;

        let data = {
          category: this.category,
          book_id: this.checkedBookData.book_id,
          word_id: this.wordData.word_id,
          memory_strength: 40 - num * 10 < 0 ? 0 : 40 - num * 10,
        };

        setWordPass(data)
          .then((res) => {
            reslove(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    async checkFalseFun(data, fun) {
      this.wordData.endTime = new Date().getTime();
      this.$set(this.wordData, "checkAnswer", data);
      clearInterval(this.countTimer);
      if (this.isReview) {
        await this.setWordPass(data);
      } else {
        await this.setEstimateWord(data);
      }
      if (!data) {
        if (this.checkedWordIndex + 3 < this.wordList.length) {
          this.wordList.splice(
            this.checkedWordIndex + 3,
            0,
            Object.assign({}, this.wordData, {
              isReview: true,
              checkAnswer: null,
            })
          );
          //
        } else {
          this.wordList.push(
            Object.assign({}, this.wordData, {
              isReview: true,
              checkAnswer: null,
            })
          );
        }
      }
      if (fun) {
        fun();
      }
    },
    goStudyCenter() {
      this.$router.push({
        name: "studyCenter",
      });
    },
    getStudyWordList() {
      let params = {
        unitId: this.unitId,
        phoneticCategory: this.$store.getters.isBritish,
        bookId: this.checkedBookData.book_id,
        number: this.checkedBookData.number,
        source: this.category,
      };
      EventBus.$emit("openLoading", {});
      getStudyWordList(params)
        .then((res) => {
          EventBus.$emit("closeLoading", {});
          if (
            res.code == 200 &&
            res.data &&
            res.data.word_pronunciation_vo_list &&
            res.data.word_pronunciation_vo_list.length > 0
          ) {
            if (
              this.groupData &&
              this.groupData.group_id &&
              this.groupData.group_id !== res.data.group_id
            ) {
              this.setInitWordNum();
              this.addIntegral(this.groupData.group_id);
            }
            res.data.word_pronunciation_vo_list.forEach((item) => {
              let paraphrase = [];
              item.word_paraphrase_vo_list.map((item2) => {
                paraphrase.push(
                  (item2.word_sex ? item2.word_sex : "") + item2.paraphrase
                );
              });
              item.id = item.word_id; //ID
              // item.name = item.word_name; //单词
              // item.phonetic = item.phonetic; //音标
              item.imgURL =
                item.word_picture_vo_list.length > 0
                  ? item.word_picture_vo_list[0].url
                  : ""; //图片
              item.exampleList = item.word_example_vo_list; //例句
              item.audioURL = item.word_audio_vo_list[0]
                ? item.word_audio_vo_list[0].url
                : ""; //音频
              item.paraphrase = paraphrase; //释义
            });
            this.checkedWordIndex = -1;
            this.groupData = res.data;
            let reviewData = res.data.word_pronunciation_vo_list.filter(
              (word) => {
                return word.is_skip == 1 && word.is_finish == 0;
              }
            );
            reviewData.forEach((item) => {
              item.isReview = true;
            });
            let studyData = res.data.word_pronunciation_vo_list.filter(
              (word) => {
                return word.is_skip == 0;
              }
            );
            this.wordList = [...reviewData, ...studyData];
            if (this.wordList.length > 0) {
              this.nextWord();
            }
          } else {
            if (this.groupData && this.groupData.group_id) {
              this.addIntegral(this.groupData.group_id);
            }
            if (!this.isOpenMessageBox) {
              this.isOpenMessageBox = true;
              this.$confirm("智能词听学习已完成,前往极速挑战", "提示", {
                confirmButtonText: "极速模式",
                cancelButtonText: "普通模式",
                showClose: true,
                distinguishCancelAndClose: true,
                closeOnClickModal: false,
                closeOnPressEscape: false,
                beforeClose: (action, instance, done) => {
                  this.$beforeConfirmClose(action, instance, done);
                },
              })
                .then(() => {
                  this.isOpenMessageBox = false;
                  this.$router.push({
                    name: "quickTest",
                    query: {
                      unitId: this.unitId,
                      category: this.category,
                    },
                  });
                })
                .catch((type) => {
                  this.isOpenMessageBox = false;
                  if (type != "close") {
                    this.$router.push({
                      name: "generalTest",
                      query: {
                        unitId: this.unitId,
                        category: this.category,
                      },
                    });
                  } else {
                    this.$router.push({
                      name: "studyCenter",
                    });
                  }
                });
            }
          }
        })
        .catch(() => {
          EventBus.$emit("closeLoading", {});
        });
    },
    setCountTimer() {
      this.countTimerNum = 5;
      if (this.countTimer) {
        clearInterval(this.countTimer);
      }
      this.countTimer = setInterval(() => {
        this.countTimerNum--;
        if (this.countTimerNum <= 0) {
          clearInterval(this.countTimer);
          this.$refs.studyWord.checkFalseFun();
        }
      }, 1000);
    },
    getMemoryReview() {
      let data = {
        page_require: {
          page_num: 1,
          page_size: 10,
        },
        category: this.category,
        book_id: this.checkedBookData.book_id,
      };
      getMemoryReview(data).then(async (res) => {
        if (res.code == 200 && res.data) {
          res.data.word_info_list.forEach((item) => {
            item.id = item.word_id; //ID
            item.name = item.word_name; //单词
            item.imgURL = item.picture_url; //图片
            item.exampleList = item.example_sentence_list; //例句
            item.paraphrase = item.paraphrase.split("\n"); //释义
            item.phonetic =
              this.$store.getters.isBritish == 1
                ? item.phonetic_british
                : item.phonetic_american; //音标
            item.audioURL =
              this.$store.getters.isBritish == 1 ? item.en_url : item.us_url; //音频
          });
          this.checkedWordIndex = -1;
          this.wordList = res.data.word_info_list.filter((item) => {
            return item.time_interval <= 0;
          });

          if (this.wordList.length > 0) {
            this.nextWord();
          } else {
            if (!this.isOpenMessageBox) {
              this.isOpenMessageBox = true;
              let nextData = await this.getReviewNumber();
              console.log(nextData);
              if (nextData) {
                this.$confirm(
                  `智能${
                    this.$store.getters.wordCategory[this.category].title
                  }已复习完成，是否前往智能${
                    this.$store.getters.wordCategory[nextData.category].title
                  }复习`,
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    closeOnClickModal: false,
                    closeOnPressEscape: false,
                  }
                )
                  .then(() => {
                    this.isOpenMessageBox = false;
                    this.$router.push({
                      name: this.$store.getters.wordCategory[nextData.category]
                        .route,
                      query: {
                        isReview: true,
                      },
                    });
                  })
                  .catch(() => {
                    this.isOpenMessageBox = false;
                    this.goStudyCenter();
                    return false;
                  });
              } else {
                this.$alert("智能词听已复习完成", "消息提示", {
                  confirmButtonText: "确定",
                  callback: () => {
                    this.isOpenMessageBox = false;
                    this.goStudyCenter();
                  },
                });
                // this.$confirm(`智能记忆已复习完成`, "提示", {
                //   confirmButtonText: "返回学习中心",
                //   cancelButtonText: "取消",
                //   closeOnClickModal: false,
                //   closeOnPressEscape: false,
                // })
                //   .then(() => {
                //     this.isOpenMessageBox = false;
                //     this.goStudyCenter();
                //   })
                //   .catch(() => {
                //     this.isOpenMessageBox = false;
                //     return false;
                //   });
              }
            }
          }
        }
      });
    },
    getStudyData() {
      if (this.isReview) {
        this.getMemoryReview();
      } else {
        this.getStudyWordList();
      }
    },
    closeTimer() {
      clearInterval(this.countTimer);
    },
    getReviewNumber() {
      return new Promise((reslove) => {
        getReviewNumber(this.checkedBookData.book_id)
          .then((res) => {
            if (res.code == 200 && res.data) {
              console.log(res);
              let data = res.data.filter((item) => {
                return item.category > this.category && item.num > 0;
              });
              if (data.length > 0) {
                reslove(data[0]);
              }
            }
            reslove(null);
          })
          .catch(() => {
            reslove(null);
          });
      });
    },
  },
  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    let data = this.checkedBookData.word_book_vo_list.filter((item) => {
      return item.source == this.category;
    });
    if (data.length > 0) {
      this.checkedBookData.number = data[0].number;
    } else {
      this.checkedBookData.number = 1;
    }
    this.unitId = this.$route.query.unitId;
    this.isReview = !!this.$route.query.isReview;
    this.getStudyData();
  },
  beforeDestroy() {
    this.closeTimer();
  },
  components: {
    StudyWord,

    Header,
    Feedback,
  },
};
</script>
